<?php

/**
 * 回复
 * @copyright (c) 2013, Mr.Wang
 * @author Mr.Wang <281762391@qq.com>
 */
class ReplyAction extends HomeAction {

    function insert() {
        $name  = $this->getActionName();
        $model = D($name);
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        //保存当前数据对象
        $list = $model->add();
        if ($list !== false) { //保存成功
            $reply = $model->find($list);
            switch ($reply['reply_type']) {
                case "店铺":
                    $this->update_shop($reply['reply_connect']);
                    break;
                case "菜品":
                    $this->update_cai($reply['reply_connect']);
                    break;
                default:
                    break;
            }

            $this->success('添加评论成功!', cookie('_currentUrl_'));
        } else {
            //失败提示
            $this->error('添加评论失败!');
        }
    }

    protected function update_shop($shop_id) {
        $where = array(
            "reply_type"    => "店铺",
            "reply_connect" => $shop_id,
        );

        $saveData = array(
            "shop_score"     => M("Reply")->where($where)->avg('reply_score'),
            "shop_reply_num" => M("Reply")->where($where)->count(),
        );
    
        M("Shop")->where("shop_id ='{$shop_id}'")->save($saveData);
            var_dump(M("Shop"));
    }

    protected function update_cai($cai_id) {
        $where = array(
            "reply_type"    => "菜品",
            "reply_connect" => $cai_id,
        );

        $saveData = array(
            "cai_score"     => M("Reply")->where($where)->avg('reply_score'),
            "cai_reply_num" => M("Reply")->where($where)->count(),
        );
        M("Cai")->where("cai_id ='{$cai_id}'")->save($saveData);
    }

}
